package com.citybox.shared.utils.jwt;

import com.citybox.shared.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {

    @Resource
    private JwtConfig jwtConfig;

    private static final String CLAIM_KEY_USERID = "uid";
    private static final String CLAIM_KEY_USERNAME = "unm";
    private static final String CLAIM_KEY_CREATED = "crt";
    private static final String CLAIM_KEY_TYPE = "typ";

    public String generateAccessToken(String userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERID, userId);
        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_TYPE, "access");

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate(jwtConfig.getAccessTokenExpire()))
                .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret())
                .compact();
    }

    public String generateRefreshToken(String userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERID, userId);
        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_TYPE, "refresh");

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate(jwtConfig.getRefreshTokenExpire()))
                .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret())
                .compact();
    }

    private Date generateExpirationDate(Long expiration) {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    public String getUserIdFromToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            Claims claims = getClaimsFromToken(token);
            return claims.get(CLAIM_KEY_USERID).toString();
        } catch (Exception e) {
            return null;
        }
    }

    public String getUsernameFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return (String) claims.get(CLAIM_KEY_USERNAME);
        } catch (Exception e) {
            return null;
        }
    }

    public String getTokenType(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return (String) claims.get(CLAIM_KEY_TYPE);
        } catch (Exception e) {
            return null;
        }
    }

    public Date getExpirationDateFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            return claims.getExpiration();
        } catch (Exception e) {
            return null;
        }
    }

    private Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(jwtConfig.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    public Boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(jwtConfig.getSecret()).parseClaimsJws(token);
            return !isTokenExpired(token);
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    public Long getAccessTokenExpire() {
        return jwtConfig.getAccessTokenExpire();
    }

    public Long getRefreshTokenExpire() {
        return jwtConfig.getRefreshTokenExpire();
    }
}
